<template>
  <div class="relative w-full max-w-2xl">
    <!-- 搜索输入框 -->
    <div class="relative">
      <input
        v-model="keyword"
        @input="handleInput"
        @focus="showDropdown = true"
        @blur="handleBlur"
        @keyup.enter="search()"
        type="text"
        placeholder="搜索"
        class="w-full px-3 py-1.5 pl-9 pr-3 text-sm text-gray-900 placeholder-gray-500 bg-gray-100 border-0 rounded-md focus:outline-none focus:ring-1 focus:ring-gray-400 focus:bg-white transition-colors"
      />
      <div class="absolute inset-y-0 left-0 flex items-center pl-3">
        <svg class="w-4 h-4 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
        </svg>
      </div>
    </div>

    <!-- 下拉面板 -->
    <Transition
      enter-active-class="transition ease-out duration-200"
      enter-from-class="opacity-0 translate-y-1"
      enter-to-class="opacity-100 translate-y-0"
      leave-active-class="transition ease-in duration-150"
      leave-from-class="opacity-100 translate-y-0"
      leave-to-class="opacity-0 translate-y-1"
    >
      <div
        v-if="showDropdown"
        class="absolute z-50 w-full mt-2 bg-white rounded-2xl shadow-2xl ring-1 ring-black ring-opacity-5"
      >
        <div class="p-4 max-h-96 overflow-y-auto">
          <!-- 搜索建议 -->
          <div v-if="suggestions.length > 0" class="mb-4">
            <h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">搜索建议</h4>
            <div class="space-y-1">
              <div
                v-for="item in suggestions"
                :key="item.id"
                @click="selectSuggestion(item.name)"
                class="flex items-center px-3 py-2 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors"
              >
                <svg class="w-4 h-4 text-gray-400 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
                <span class="text-sm text-gray-700" v-html="highlightKeyword(item.name)"></span>
              </div>
            </div>
          </div>

          <!-- 搜索历史 -->
          <div v-if="!keyword && searchHistory.length > 0" class="mb-4">
            <div class="flex items-center justify-between mb-2">
              <h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide">搜索历史</h4>
              <button
                @click="clearHistory"
                class="text-xs text-gray-500 hover:text-gray-700 transition-colors"
              >
                清空
              </button>
            </div>
            <div class="space-y-1">
              <div
                v-for="item in searchHistory"
                :key="item.id"
                class="flex items-center justify-between px-3 py-2 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors group"
                @click="search(item.keyword)"
              >
                <div class="flex items-center flex-1">
                  <svg class="w-4 h-4 text-gray-400 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                  <span class="text-sm text-gray-700">{{ item.keyword }}</span>
                </div>
                <button
                  @click.stop="removeHistory(item.id)"
                  class="opacity-0 group-hover:opacity-100 text-gray-400 hover:text-gray-600 transition-all"
                >
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>
            </div>
          </div>

          <!-- 热门搜索 -->
          <div v-if="!keyword && hotSearches.length > 0">
            <h4 class="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">热门搜索</h4>
            <div class="flex flex-wrap gap-2">
              <button
                v-for="(item, index) in hotSearches"
                :key="item.id"
                @click="search(item.keyword)"
                class="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm rounded-full transition-all"
                :class="index < 3 
                  ? 'bg-gradient-to-r from-amber-50 to-amber-100 text-amber-900 hover:from-amber-100 hover:to-amber-200' 
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'"
              >
                <span class="inline-flex items-center justify-center w-4 h-4 text-xs font-semibold rounded-full"
                  :class="index < 3 ? 'bg-amber-500 text-white' : 'bg-gray-300 text-gray-600'"
                >
                  {{ index + 1 }}
                </span>
                {{ item.keyword }}
                <svg v-if="index < 3" class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M12.395 2.553a1 1 0 00-1.45-.385c-.345.23-.614.558-.822.88-.214.33-.403.713-.57 1.116-.334.804-.614 1.768-.84 2.734a31.365 31.365 0 00-.613 3.58 2.64 2.64 0 01-.945-1.067c-.328-.68-.398-1.534-.398-2.654A1 1 0 005.05 6.05 6.981 6.981 0 003 11a7 7 0 1011.95-4.95c-.592-.591-.98-.985-1.348-1.467-.363-.476-.724-1.063-1.207-2.03zM12.12 15.12A3 3 0 017 13s.879.5 2.5.5c0-1 .5-4 1.25-4.5.5 1 .786 1.293 1.371 1.879A2.99 2.99 0 0113 13a2.99 2.99 0 01-.879 2.121z"/>
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { router } from '@inertiajs/vue3'
import { debounce } from 'lodash'

const keyword = ref('')
const showDropdown = ref(false)
const suggestions = ref([])
const searchHistory = ref([])
const hotSearches = ref([])

// 输入处理（防抖）
const handleInput = debounce(async () => {
  if (keyword.value.length < 2) {
    suggestions.value = []
    return
  }

  try {
    const response = await fetch(`/api/search/suggestions?q=${encodeURIComponent(keyword.value)}`)
    suggestions.value = await response.json()
  } catch (error) {
    console.error('获取搜索建议失败:', error)
  }
}, 300)

// 执行搜索
const search = (searchKeyword = null) => {
  const q = searchKeyword || keyword.value
  // 确保 q 是字符串类型
  const queryString = String(q || '').trim()
  if (!queryString) return

  router.get(route('search.index', { q: queryString }))
  showDropdown.value = false
  keyword.value = ''
}

// 选择建议
const selectSuggestion = (text) => {
  keyword.value = text
  search()
}

// 高亮关键词
const highlightKeyword = (text) => {
  if (!keyword.value) return text
  const regex = new RegExp(`(${keyword.value})`, 'gi')
  return text.replace(regex, '<mark class="bg-yellow-200 font-semibold">$1</mark>')
}

// 加载数据
const loadData = async () => {
  try {
    const [historyRes, hotRes] = await Promise.all([
      fetch('/api/search/history'),
      fetch('/api/search/hot')
    ])

    searchHistory.value = await historyRes.json()
    hotSearches.value = await hotRes.json()
  } catch (error) {
    console.error('加载搜索数据失败:', error)
  }
}

// 删除单条历史
const removeHistory = async (id) => {
  try {
    await fetch(`/api/search/history/${id}`, { method: 'DELETE' })
    searchHistory.value = searchHistory.value.filter(item => item.id !== id)
  } catch (error) {
    console.error('删除搜索历史失败:', error)
  }
}

// 清空历史
const clearHistory = async () => {
  try {
    await fetch('/api/search/history', { method: 'DELETE' })
    searchHistory.value = []
  } catch (error) {
    console.error('清空搜索历史失败:', error)
  }
}

// 失焦处理
const handleBlur = () => {
  setTimeout(() => {
    showDropdown.value = false
  }, 200)
}

// 初始化
onMounted(() => {
  loadData()
})
</script>

